window.addEventListener('load', () => {
	const heatmapContainer = document.querySelector('.heatmap');
	const selectedCountElement = document.querySelector('#selected-count');
	const percentageElement = document.querySelector('#percentage');
	const squares = [];
	let startSquare = null;

	const startDate = new Date('2021-07-01');
	const endDate = new Date('2023-07-31');
	const currentDate = new Date();

	// Generate squares for each day
	for (let day = startDate; day <= endDate; day.setDate(day.getDate() + 1)) {
		const square = document.createElement('div');
		square.classList.add('square');
		if (day <= currentDate) {
			square.classList.add('active');
		}
		if (day.toDateString() === currentDate.toDateString()) {
			square.classList.add('highlight');
		}
		heatmapContainer.appendChild(square);
		squares.push(square);
	}

	let isSelecting = false;
	let selectedCount = 0;

	heatmapContainer.addEventListener('mousedown', (event) => {
		const target = event.target;
		isSelecting = true;
		startSquare = target;
		squares.forEach(square => {
			square.classList.remove('selected');
		});
	});

	heatmapContainer.addEventListener('mouseup', (event) => {
		isSelecting = false;
		const endSquare = event.target;
		const startIndex = squares.indexOf(startSquare);
		const endIndex = squares.indexOf(endSquare);

		const [minIndex, maxIndex] = [startIndex, endIndex].sort((a, b) => a - b);

		for (let i = minIndex; i <= maxIndex; i++) {
			squares[i].classList.add('selected');
		}

		updateSelectionInfo();
	});

	function updateSelectionInfo() {
		const activeSquares = squares.filter(square => square.classList.contains('active'));
		selectedCount = squares.filter(square => square.classList.contains('selected')).length;
		const percentage = ((selectedCount / activeSquares.length) * 100).toFixed(2);
		selectedCountElement.textContent = selectedCount;
		percentageElement.textContent = `${percentage}%`;
	}

	squares.forEach(square => {
		square.addEventListener('mouseover', () => {
			if (isSelecting) {
				square.classList.add('selected');
				updateSelectionInfo();
			}
		});

		square.addEventListener('click', () => {
			square.classList.toggle('selected');
			updateSelectionInfo();
		});
	});
});